﻿using ERPSystem.Common.Domains.UserCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using System.Security.Cryptography;
using System.Text;

namespace RBACCommon.API.RBACCommons.UserLogin
{
    public class UserLoginsQueryHandler : IRequestHandler<UserLoginsQueryCommand, Result>
    {
        private readonly IBaseRepository<Employee> _usersRepository;

        public UserLoginsQueryHandler(IBaseRepository<Employee> usersRepository)
        {
            _usersRepository = usersRepository;
        }





        /// <summary>
        /// 用户登录业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(UserLoginsQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code=(int)CommonErrorCode.Search };
            try
            { 
                //密码加密
                request.Password = Md5(request.Password);
                var login = await (await _usersRepository.GetAll()).Where(c => c.EmployeeName == request.EmployeeName&& c.Password == request.Password).ToListAsync();
                //var login = await (await _usersRepository.GetAll()).Where(c => c.UserName == request.UserName).ToListAsync();
                if (login.Count() > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "登陆成功";
                }
                else
                {
                    result.Code = (int)CommonErrorCode.Search; 
                    result.Msg = "登陆失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
        /// <summary>
        /// Md5加密
        /// </summary>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public static string Md5(string passWord)
        {
            var md5 = MD5.Create();
            var str = md5.ComputeHash(Encoding.UTF8.GetBytes(passWord));
            return BitConverter.ToString(str).Replace("-", "").ToLower();
        }

    }
}
